<template>
  <div class="edit-popup">
    <popup
      ref="popupRef"
      :title="popupTitle"
      :async="true"
      width="550px"
      @confirm="handleSubmit"
      @close="handleClose"
    >
      <el-form ref="formRef" :model="formData" label-width="90px">
        <el-form-item label="是否匿名" prop="is_anonymous">
          <el-switch v-model="formData.is_anonymous" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="头像" prop="activity_id">
          <el-upload
            class="avatar-uploader"
            :action="action"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="formData.image" :src="formData.image" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="评论内容" prop="content">
          <el-input v-model="formData.content" type="textarea" clearable placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="点赞数" prop="zan">
          <el-input v-model="formData.zan" type="number" clearable placeholder="请输入点赞数" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="formData.nickname" clearable placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="评分" prop="score">
          <el-rate v-model="formData.score" allow-half :colors="['#99A9BF', '#F7BA2A', '#FF9900']" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status" class="ml-4">
            <el-radio label="0" size="large">未审核</el-radio>
            <el-radio label="1" size="large">已审核</el-radio>
            <el-radio label="-1" size="large">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </popup>
  </div>
</template>

<script lang="ts" setup name="zgPlayerCommentEdit">
import type { FormInstance } from "element-plus"
import Popup from "@/components/popup/index.vue"
import type { UploadProps, UploadUserFile } from "element-plus"
import config from "@/config"
import {
  apiZgPlayerCommentAdd,
  apiZgPlayerCommentEdit,
  apiZgPlayerCommentDetail,
} from "@/api/zg_player_comment"
import { timeFormat } from "@/utils/util"
import type { PropType } from "vue"
defineProps({
  dictData: {
    type: Object as PropType<Record<string, any[]>>,
    default: () => ({}),
  },
})
const emit = defineEmits(["success", "close"])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref("add")

// 弹窗标题
const popupTitle = computed(() => {
  return mode.value == "edit" ? "编辑选手评论表" : "新增选手评论表"
})

// 表单数据
const formData = reactive({
  id: "",
  is_anonymous: "",
  image: "",
  nickname: "",
  zan: "",
  content: "",
  status: "",
  score: "",
})

// 上传图片
const imageUrl = ref("")
const action = ref(`${config.baseUrl}${config.urlPrefix}/upload/`)
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response: any,
  uploadFile: { raw: any }
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  formData.image = URL.createObjectURL(uploadFile.raw!)
}

// 表单验证
const formRules = reactive<any>({
  activity_id: [
    {
      required: true,
      message: "请输入活动id",
      trigger: ["blur"],
    },
  ],
  status: [
    {
      required: true,
      message: "请输入状态（0未审核，1已审核，2禁用）",
      trigger: ["blur"],
    },
  ],
  player_id: [
    {
      required: true,
      message: "请输入选手id",
      trigger: ["blur"],
    },
  ],
  user_id: [
    {
      required: true,
      message: "请输入用户id",
      trigger: ["blur"],
    },
  ],
  is_anonymous: [
    {
      required: true,
      message: "请输入是否匿名（1是，0否）",
      trigger: ["blur"],
    },
  ],
})

// 获取详情
const setFormData = async (data: Record<any, any>) => {
  for (const key in formData) {
    if (data[key] != null && data[key] != undefined) {
      //@ts-ignore
      formData[key] = data[key]
    }
  }
}

const getDetail = async (row: Record<string, any>) => {
  const data = await apiZgPlayerCommentDetail({
    id: row.id,
  })
  setFormData(data)
}

// 提交按钮
const handleSubmit = async () => {
  await formRef.value?.validate()
  const data = { ...formData }
  mode.value == "edit"
    ? await apiZgPlayerCommentEdit(data)
    : await apiZgPlayerCommentAdd(data)
  popupRef.value?.close()
  emit("success")
}

//打开弹窗
const open = (type = "add") => {
  mode.value = type
  popupRef.value?.open()
}

// 关闭回调
const handleClose = () => {
  emit("close")
}

defineExpose({
  open,
  setFormData,
  getDetail,
})
</script>

<style scoped lang="scss">
.avatar-uploader .avatar {
  width: 5rem;
  height: 5rem;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 5rem;
  height: 5rem;
  text-align: center;
  background: #efefef;
}
</style>
